<template>
  <div>
    <div style="margin-bottom: 30px">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div style="margin: 10px 0">
      <el-select v-model="cid" placeholder="请选择商品类别" class="mr-5">
        <el-option
            v-for="item in category"
            :key="item.cid"
            :label="item.cname"
            :value="item.cid">
        </el-option>
      </el-select>
      <el-input style="width: 200px" placeholder="请输入商品名称"
                v-model="gname" suffix-icon="el-icon-search"></el-input>
      <el-input style="width: 200px" placeholder="请输入生产商"
                v-model="producer" suffix-icon="el-icon-office-building" class="ml-5 mr-5"></el-input>
      <el-button class="ml-5" type="primary" @click="search">搜索</el-button>
      <el-button class="ml-5" type="warning" @click="reset">重置</el-button>
    </div>

    <div style="margin: 10px 0">
      <el-button type="primary" @click="handleAdd" class="mr-5">新增 <i class="el-icon-circle-plus-outline"></i>
      </el-button>
      <el-popconfirm
          confirm-button-text='确定'
          cancel-button-text='再想想'
          icon="el-icon-info"
          icon-color="red"
          title="确定批量删除吗？"
          @confirm="delBatch">
        <el-button type="danger" slot="reference" class="mr-5">批量删除 <i class="el-icon-remove-outline"></i></el-button>
      </el-popconfirm>
      <el-button type="primary" @click="sortByInventory" class="mr-5">按库存数量排序 <i class="el-icon-sort"></i>
      </el-button>
    </div>
    <el-table :data="tableData.slice(startIndex,startIndex+pageSize)" border stripe
              @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column prop="gid" label="id" width="80">
      </el-table-column>
      <el-table-column prop="category.cname" label="商品类别" width="120">
      </el-table-column>
      <el-table-column prop="gname" label="商品名称" width="120">
      </el-table-column>
      <el-table-column prop="price" label="价格(元)" width="80">
      </el-table-column>
      <el-table-column prop="inventory" label="库存数量" width="80">
      </el-table-column>
      <el-table-column prop="description" label="商品描述" width="200">
      </el-table-column>
      <el-table-column prop="producer" label="生产商" width="200">
      </el-table-column>
      <el-table-column prop="" label="图片" width="120" align="center">
        <template slot-scope="scope">
          <img :src="scope.row.photo" alt="" style="width: 50px;height: 50px"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="" align="center">
        <template slot-scope="scope">
          <el-button type="success" @click="handleEdit(scope.row)" class="mr-5">
            编辑<i class="el-icon-edit"></i>
          </el-button>
          <el-popconfirm
              confirm-button-text='确定'
              cancel-button-text='再想想'
              icon="el-icon-info"
              icon-color="red"
              title="确定删除吗？"
              @confirm="del(scope.row.gid)">
            <el-button type="danger" slot="reference">删除 <i class="el-icon-remove-outline"></i></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div style="padding: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[5, 10, 15, 20]"
          :page-size=pageSize
          layout="total, sizes, prev, pager, next, jumper"
          :total=total>
      </el-pagination>
    </div>
    <!--    商品信息的弹窗    -->
    <el-dialog title="商品信息" :visible.sync="dialogFormVisible" width="30%">
      <el-form :model="goods" :rules="rules" ref="goods">
        <el-form-item label="商品类别" label-width="100px" prop="cid">
          <el-select v-model="goods.cid" placeholder="请选择商品类别">
            <el-option
                v-for="item in category"
                :key="item.cid"
                :label="item.cname"
                :value="item.cid">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称" label-width="100px" prop="gname">
          <el-input v-model="goods.gname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="价格(元)" label-width="100px" prop="price">
          <el-input v-model="goods.price" autocomplete="off" type="number"></el-input>
        </el-form-item>
        <el-form-item label="库存数量" label-width="100px" prop="price">
          <el-input v-model="goods.inventory" autocomplete="off" type="number"></el-input>
        </el-form-item>
        <el-form-item label="商品描述" label-width="100px" prop="description">
          <el-input v-model="goods.description" autocomplete="off" type="textarea" autosize></el-input>
        </el-form-item>
        <el-form-item label="生产商" label-width="100px" prop="producer">
          <el-input v-model="goods.producer" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图片" label-width="100px" prop="">
          <el-upload
              class="avatar-uploader"
              action="http://localhost/file/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
            <img v-if="goods.photo" :src="goods.photo" class="avatar" alt="">
            <img v-else-if="imageUrl" :src="imageUrl" class="avatar" alt="">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible=false">取 消</el-button>
        <el-button type="primary" @click="save('goods')">{{ btnText }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";
export default {
  name: "Goods",
  data() {
    return {
      tableData: [],
      startIndex: 0,
      gname:"",
      producer:"",
      cid: "",
      pageSize: 5,
      total: 0,
      dialogFormVisible: false,
      btnText: "",
      goods: {},
      category:{},
      multipleSelection: [],
      imageUrl: '',
      isAscending:false,
      rules: {
        cid: [
          {required: true, message: '请选择商品类别', trigger: 'blur'},
        ],
        gname: [
          {required: true, message: '商品名称', trigger: 'blur'},
        ],
        price: [
          {required: true, message: '请输入价格', trigger: 'blur'},
        ],
        inventory: [
          {required: true, message: '请输入库存数量', trigger: 'blur'},
        ],
        phone: [
          {required: true, message: '请输入商品描述', trigger: 'blur'},
        ],
        producer: [
          {required: true, message: '请输入生产商名称', trigger: 'blur'},
        ],
      },
    }
  },
  created() {
    this.load()
    request.get("/category/findall").then(res => {
      this.category = res
    })
  },
  methods: {
    load() {
      request.get("/goods/findall").then(res => {
        this.tableData = res
        this.total = this.tableData.length
        this.startIndex=0
      })
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
    },
    handleCurrentChange(pageNum) {
      this.startIndex = (pageNum - 1) * this.pageSize
    },
    handleAdd() {
      this.btnText = "添加"
      this.goods = {}
      this.dialogFormVisible = true
    },
    handleEdit(row) {
      this.btnText = "修改"
      this.dialogFormVisible = true
      this.goods = Object.assign({}, row)
      console.log(this.goods)
    },
    save(goods) {
      this.$refs[goods].validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false
          request.post("goods/save",this.goods).then(res=>{
            if (res){
              this.$message.success(this.btnText + "成功")
              this.load()
              this.imageUrl=""
            }else {
              this.$message.error(this.btnText + "失败")
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    del(id) {
      request.post("goods/delete",id).then(res=>{
        if (res){
          this.$message.success( "删除成功")
          this.load()
        }else {
          this.$message.error( "删除失败")
        }
      })
      console.log(id)
    },
    handleSelectionChange(val) {
      // console.log(val)
      this.multipleSelection = val
    },
    delBatch() {
      //map函数：数组的每个元素都执行一个给定的函数，返回值仍为一个数组
      let ids = this.multipleSelection.map(v => v.gid)
      if(ids.length!==0){
        request.post("goods/deleltebatch",ids).then(res=>{
          if (res){
            this.$message.success( "批量删除成功")
            this.load()
          }else {
            this.$message.error( "批量删除失败")
          }
        })
      }else {
        this.$message.warning( "请选择要删除的数据")
      }
    },
    search(){
      request.get("/goods/selectbycondition",{
        params:{
          gname:this.gname,
          cid:this.cid,
          producer:this.producer,
        }
      }).then(res => {
        this.tableData = res
        this.total = this.tableData.length
        this.startIndex=0
      })
    },
    reset(){
      this.username=""
      this.gname=""
      this.gender=""
      this.load()
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.goods.photo=res
    },
    beforeAvatarUpload(file) {
      const isJPG_PNG = file.type === 'image/jpeg'||file.type ==='image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG_PNG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG_PNG && isLt2M;
    },
    sortByInventory(){
      if(this.isAscending){
        this.tableData.sort((a,b)=>a.inventory-b.inventory)
        this.isAscending=false
      }else {
        this.tableData.sort((a,b)=>b.inventory-a.inventory)
        this.isAscending=true
      }

    }
  }
}
</script>

<style scoped>
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
}
.avatar-uploader:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>